package com.ljx.Controller;

import com.ljx.Domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String realPath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("upload")
    public R<String> fileUpload(MultipartFile file){
        log.info("{}",file);
        //MultipartFile生成的是临时文件，需要将他保存在本地
        String originalFilename = file.getOriginalFilename();
        //获取前台图片的后缀，用于拼接
        String suffix = originalFilename.substring(originalFilename.indexOf("."));
        //使用雪花算法生成名字
        String filename = UUID.randomUUID().toString()+suffix;
        //真实路径
        String path = realPath+filename;
        log.info("图片保存路径：{}",path);
        try {
            //判断文件是否存在
            File fileImage = new File(path);
            if(!fileImage.exists()){
                fileImage.mkdirs();
            }
            file.transferTo(fileImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response){
        //通过输入流，将文件输入进内存
        try (  FileInputStream fileInputStream = new FileInputStream(realPath+name);
               ServletOutputStream outputStream = response.getOutputStream()){
            byte[] b = new byte[1024];
            int len = 0;
            while ((len=fileInputStream.read(b))!=-1){
                //通过输出流，将文件输出到response流中
                outputStream.write(b,0,len);
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
